﻿using Airborne.ScrumPoker.Module.Developer.Views;
using Airborne.ScrumPoker.Module.Events;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Composite.Wpf.Events;
using Microsoft.Practices.Unity;

namespace Airborne.ScrumPoker.Module.Developer.Controllers
{
    public class TimerController : ITimerController
    {
        #region Constructor
        public TimerController(IRegionManager regionManager, IEventAggregator eventAggregator, IUnityContainer container)
        {
            RegionManager = regionManager;
            EventAggregator = eventAggregator;
            Container = container;
        }
        #endregion

        #region Properties
        private IRegionManager RegionManager { get; set; }
        private IEventAggregator EventAggregator { get; set; }
        private IUnityContainer Container { get; set; }
        private ITimerView TimerView { get; set; }
        #endregion

        #region Methods
        public void Run()
        {
            SubscribeToEvents();
            TimerView = Container.Resolve<ITimerView>();
            TimerView.Timer = new CountdownTimer();
            RegionManager.Regions[RegionNames.TimerRegion].AddAndActivate(TimerView);
        }

        private void SubscribeToEvents()
        {
            EventAggregator.GetEvent<GenericEvent<int>>().Subscribe(TimerStarted, ThreadOption.UIThread, true, p => p.Topic == EventTopics.StartTimer);
            EventAggregator.GetEvent<GenericEvent<string>>().Subscribe(TimerEnded, ThreadOption.UIThread, true, p => p.Topic == EventTopics.StopTimer);
        }

        private void TimerStarted(EventParameters<int> parameters)
        {
            TimerView.ResetCounter(parameters.Value);   
            TimerView.Timer.Start(parameters.Value);
        }

      

        private void TimerEnded(EventParameters<string> parameters)
        {
            TimerView.Timer.Stop();
        }
        #endregion
    }
}
